package com.soso.confidant.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import com.soso.confidant.pojo.Amass;
import com.soso.confidant.util.DB;

public class TasteDaoImpl implements TasteDao {
	
	public ArrayList<Amass> getAmasses(ArrayList<String> words, String openid, int max) {
		ArrayList<Amass> amasses = new ArrayList<Amass>();
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		//System.out.println(page);
		try {
			conn = DB.getConnection();
			stmt=conn.createStatement();
			String sql = "select * from amass where openid='"+openid+"' and word='";
			sql = sql+words.get(0)+"' ";
			for(int i=1;i<words.size();i++){
				sql = sql+"or word='"+words.get(i)+"' ";
			}
			sql = sql+"order by id desc limit "+max;
			//System.out.println(sql);
			rs=stmt.executeQuery(sql);
			while(rs.next()){
					Amass amass = new Amass();
					amass.setId(rs.getInt("id"));
					amass.setOpenid(rs.getString("openid"));
					String word = rs.getString("word");
					amass.setWord(word);
					String title = rs.getString("title").replaceAll(word, "<em>"+word+"</em>");
					//System.out.println(title);
					amass.setTitle(title);
					amass.setHref(rs.getString("href"));
					amasses.add(amass);
			}
		}catch (SQLException ex) {
			// handle any errors
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
		}finally {
			close(conn,stmt,rs);
		}
		return amasses;
	}
	
	public void close(Connection conn,Statement stmt,ResultSet rs){
		try {
			if(rs != null) {
				rs.close();
				rs = null;
			}
			if(stmt != null) {
				stmt.close();
				stmt = null;
			}
			if(conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void close(Connection conn,PreparedStatement pstmt){
		try {
			if(pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
			if(conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
